package zhibi.wechat.mp.service.impl;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMaterialService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zhibi.wechat.mp.domain.NewsArticle;
import zhibi.wechat.mp.domain.NewsItem;
import zhibi.wechat.mp.extra.base.BaseServiceImpl;
import zhibi.wechat.mp.mapper.NewsArticleMapper;
import zhibi.wechat.mp.mapper.NewsItemMapper;
import zhibi.wechat.mp.service.NewsService;

import java.util.Date;

@Service
@Transactional
public class NewsServiceImpl extends BaseServiceImpl<NewsItem> implements NewsService {

    @Autowired
    public NewsServiceImpl(NewsItemMapper mapper) {
        super(mapper);
    }

    @Autowired
    private NewsArticleMapper newsArticleMapper;
    @Autowired
    private NewsItemMapper newsItemMapper;
    @Autowired
    private WxMpService wxMpService;

    @Override
    public String insertArticle(NewsArticle article) throws WxErrorException {
        //保存到微信
        WxMpMaterialService materialService = wxMpService.getMaterialService();
        WxMpMaterialNews news = new WxMpMaterialNews();
        news.setCreatedTime(new Date());
        news.setUpdatedTime(new Date());
        WxMpMaterialNews.WxMpMaterialNewsArticle wxMpMaterialNewsArticle = new WxMpMaterialNews.WxMpMaterialNewsArticle();
        BeanUtils.copyProperties(article, wxMpMaterialNewsArticle);
        news.getArticles().add(wxMpMaterialNewsArticle);
        WxMpMaterialUploadResult uploadResult = materialService.materialNewsUpload(news);

        //保存数据库
        newsArticleMapper.insertSelective(article);
        NewsItem newsItem = new NewsItem();
        newsItem.setMediaId(uploadResult.getMediaId());
        newsItem.setUpdatedTime(new Date());
        newsItem.setCreatedTime(new Date());
        newsItem.setArticles(article.getTitle());
        newsItem.setArticleids(article.getId() + "#");
        newsItemMapper.insertSelective(newsItem);
        return uploadResult.getMediaId();
    }

}
